package org.cs456.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class Db {
	private SQLiteDatabase db;
	private DbOpenHelper dbHelper;
	private Context context;

	public Db(Context ctxt) {
		context = ctxt;
		dbHelper = new DbOpenHelper(context, DbConstants.DB_NAME, null, DbConstants.DB_VERSION);
	}
	
	public void open() throws SQLiteException{
		try{
			db = dbHelper.getWritableDatabase();
		}catch(SQLiteException ex){
			Log.v("SQLiteException Caught", ex.getMessage());
			db = dbHelper.getReadableDatabase();
		}
	}
	
	public void close(){
		db.close();
	}

	protected void finalize() {
		if (db.isOpen())
			db.close();
	}

	public Cursor findImage(int imgId){
		return db.query(DbConstants.IMAGE_TABLE, null, "id = ?", new String[] {""+imgId}, null, null, null, "1");
	}

	public String getString(String key) {
		db = dbHelper.getReadableDatabase();
		Cursor c = db.rawQuery("SELECT * FROM " + DbConstants.STRING_TABLE
				+ " where key = '" + key + "'", null);
		int colIndex = c.getColumnIndex("value");
		c.moveToFirst();
		String ret = c.getString(colIndex);
		c.close();
		db.close();
		return ret;
	}

	public void insert(Image image) {
		ContentValues cv = new ContentValues();
		cv.put("path", image.getFilePath());
		cv.put("name", image.getName());
		Log.d("CS456", "Inserting image into row " + db.insert(DbConstants.IMAGE_TABLE, null, cv));
	}

	public long count(String imageTable) {
		return DatabaseUtils.queryNumEntries(db, DbConstants.IMAGE_TABLE);
	}
}
